package com.bnz.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 类名：
 * 作者：WF
 * 功能：登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

	/**
	 * 1. 判断用户是否曾经登录过,如果登录过，就在session中有用户
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//1.1 得到session对象
		HttpSession session = request.getSession();
		//1.2 从session中取得用户名
		String username = (String) session.getAttribute("username");
		//1.3 判断username是否有值，如果有，就证明曾经登录成功过,否则，就没有登录，就跳转到登录页面重新登录
		if(username == null){
			response.sendRedirect("/login.html");
			return false;
		}
		return true;
	}
}
